"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments)).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;
    return { next: verb(0), "throw": verb(1), "return": verb(2) };
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [0, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var mongodb = require("mongodb");
var common = require("../../../common");
var User = require("../../../models/user");
var Room = require("../../../models/room");
var Player = require("../../../models/player");
var Friend = require("../../../models/friend");
var Game = require("../../../models/game");
var GiftRecord = require("../../../models/giftRecord");
var RealGitRecordInfo = require("../../../models/gitRecordInfo");
module.exports = function (app) {
    return new Remote(app);
};
var Remote = function (app) {
    this.app = app;
    this.channelService = app.get('channelService');
};
var remote = Remote.prototype;
// ************************************ Request
/**
 * @see :  match  首页直接点击进去
 */
remote.matching = function (uid, mode, index, maxUserCount, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, room;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    // index =1;
                    // if(mode==2){
                    // 	mode=1;
                    // }else{
                    // 	mode=2;
                    // }
                    mode == 2 ? mode = 1 : mode = 2;
                    return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(-1);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Room.Model.findOne({
                            mode: mode,
                            isStart: false,
                            index: index,
                            players: { $size: maxUserCount },
                            // players: { $size: maxUserCount, $in: [null] },
                            // players: { $size: maxUserCount, $elemMatch: { "$in": [null], "$exists": true } },
                            password: "",
                            isLive: false,
                        }).$where("this.players.indexOf(null) >= 0").exec()];
                case 2:
                    room = _a.sent();
                    if (!!room)
                        return [3 /*break*/, 4];
                    return [4 /*yield*/, Room.create(mode, index, maxUserCount, "", user, false)];
                case 3:
                    room = (_a.sent());
                    _a.label = 4;
                case 4:
                    if (!room) {
                        console.warn("!room");
                        cb(-1);
                        return [2 /*return*/];
                    }
                    cb(room.number);
                    return [2 /*return*/];
            }
        });
    });
};
/**
 * @see  点击创建房间  create
 */
remote.create = function (uid, mode, index, maxUserCount, password, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, room;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    mode == 2 ? mode = 1 : mode = 2;
                    return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(-1);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Room.create(mode, index, maxUserCount, password, user, false)];
                case 2:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb(-1);
                        return [2 /*return*/];
                    }
                    cb(room.number);
                    return [2 /*return*/];
            }
        });
    });
};
remote.createLive = function (uid, mode, index, maxUserCount, password, isLive, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, room;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(-1);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Room.create(mode, index, maxUserCount, password, user, true)];
                case 2:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb(-1);
                        return [2 /*return*/];
                    }
                    cb(room.number);
                    return [2 /*return*/];
            }
        });
    });
};
remote.enter = function (uid, roomNumber, password, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, room;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(0);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Room.Model.findOne({ number: roomNumber }).exec()];
                case 2:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb(0);
                        return [2 /*return*/];
                    } // 房間不存在
                    if (!room.players.find(function (p) { return !!p && p.user._id.equals(uid); }) && room.password) {
                        if (!password) {
                            console.warn("!password");
                            cb(2);
                            return [2 /*return*/];
                        } // 需要密碼
                        if (room.password != password) {
                            console.warn("room.password != password");
                            cb(3);
                            return [2 /*return*/];
                        } // 密碼錯誤
                    }
                    //不是主播房   并且  发现  存在不在线的人
                    if (!room.isLive && (room.players.filter(function (p) { return !!p && p._id; }).length == 12)) {
                        // || room.players.findIndex(p => !!p && p.user._id == uid) > -1)
                        //房间有主播  并且是主播房间
                        if (room.isStart && room.players.findIndex(function (p) { return !!p && p.user._id == uid; }) > -1 || room.isLive && !!room.owner) {
                        }
                        else {
                            console.warn("房间不是主播房，并且人数达到12人不能进入房间！");
                            cb(4);
                            return [2 /*return*/];
                        }
                    }
                    //主播间 碧并且  没有博主在里面  不能进
                    if (room.isLive && !room.owner && !user.isAnchor) {
                        console.warn("主播间，没有主播在直播！");
                        cb(5);
                        return [2 /*return*/];
                    }
                    if (room.isLive) {
                        room.dayRounds = [];
                    }
                    return [4 /*yield*/, User.pushMessage(this.app, user._id.toString(), "onSyncRoom", room)];
                case 3:
                    _a.sent();
                    return [4 /*yield*/, Room.addUser(this.app, room, user)];
                case 4:
                    room = _a.sent();
                    cb(1);
                    return [2 /*return*/];
            }
        });
    });
};
remote.updateSelects = function (roomId, uid, selects, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, room, player, _loop_1, i, state_1;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(0);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 2:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb(0);
                        return [2 /*return*/];
                    }
                    player = room.players.find(function (p) { return !!p && p.user._id.equals(user._id); });
                    if (!player) {
                        console.warn("!player");
                        cb(0);
                        return [2 /*return*/];
                    }
                    if (selects.length != player.selectedPlayers.length) {
                        console.warn("selects.length != player.selectedPlayers.length");
                        cb(0);
                        return [2 /*return*/];
                    }
                    _loop_1 = function (i) {
                        var select = selects[i];
                        if (!select)
                            return "continue";
                        if (!player.selectablePlayers.find(function (sap) { return sap.toString() == select; })) {
                            console.warn("!player.selectablePlayers.find(sap => sap.toString() == select)");
                            cb(0);
                            return { value: void 0 };
                        } // 你不能選該目標
                    };
                    for (i = 0; i < selects.length; i++) {
                        state_1 = _loop_1(i);
                        if (typeof state_1 === "object")
                            return [2 /*return*/, state_1.value];
                    }
                    if (room.roundId == "参选警长") {
                        player.leaderState = selects.indexOf("") >= 0 ? 0 : 1;
                    }
                    player.selectedPlayers = selects.map(function (s) { return !!s ? new mongodb.ObjectID(s) : null; });
                    return [4 /*yield*/, Room.sync(this.app, room)];
                case 3:
                    room = _a.sent();
                    return [4 /*yield*/, Room.sync(this.app, room)];
                case 4:
                    // let statusService = this.app.get('statusService');
                    // statusService.pushByUids(
                    // 	[user._id.toString()],
                    // 	"onSyncRoom",
                    // 	room, function(err, fails) { cb(1); }
                    // );
                    room = _a.sent();
                    cb(1);
                    return [2 /*return*/];
            }
        });
    });
};
remote.changePassword = function (roomId, uid, newPw, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var room, player;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 1:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb();
                        return [2 /*return*/];
                    }
                    player = room.players.find(function (p) { return !!p && p.user._id.equals(uid); });
                    if (!player) {
                        console.warn("!player");
                        cb();
                        return [2 /*return*/];
                    }
                    if (!Room.isOwnerEquals(room, player.user._id)) {
                        console.warn("!Room.isOwnerEquals(room, player.user._id)");
                        cb();
                        return [2 /*return*/];
                    }
                    room.password = newPw;
                    return [4 /*yield*/, Room.sync(this.app, room)];
                case 2:
                    room = _a.sent();
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
// ************************************ Notify
remote.ready = function (roomId, uid, isReady, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, room, player;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 2:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb();
                        return [2 /*return*/];
                    }
                    if (room.isStart) {
                        console.warn("room.isStart");
                        cb();
                        return [2 /*return*/];
                    }
                    player = room.players.find(function (p) { return !!p && p.user._id.equals(user._id); });
                    if (!player) {
                        console.warn("!player");
                        cb();
                        return [2 /*return*/];
                    }
                    if (player.isReady == isReady) {
                        console.warn("player.isReady == isReady");
                        cb();
                        return [2 /*return*/];
                    }
                    player.isReady = isReady;
                    return [4 /*yield*/, Room.sync(this.app, room)];
                case 3:
                    room = _a.sent();
                    // RoomFunction.checkAllReady(this.app, room);
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
remote.start = function (roomId, uid, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var room, player;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 1:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb();
                        return [2 /*return*/];
                    }
                    if (room.isStart) {
                        console.warn("room.isStart");
                        cb();
                        return [2 /*return*/];
                    }
                    if (room.players.indexOf(null) >= 0) {
                        console.warn("room.players.indexOf(null) >= 0");
                        cb();
                        return [2 /*return*/];
                    }
                    player = room.players.find(function (p) { return !!p && p.user._id.equals(uid); });
                    if (!player) {
                        console.warn("!player");
                        cb();
                        return [2 /*return*/];
                    }
                    if (!Room.isOwnerEquals(room, player.user._id)) {
                        console.warn("!Room.isOwnerEquals(room, player.user._id)");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Room.nextRound(this.app, room, "游戏开始")];
                case 2:
                    _a.sent();
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
remote.addRobot = function (roomId, uid, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, room, robot;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 2:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, User.Model.findOne({ platform: "", openId: "robot" }).exec()];
                case 3:
                    robot = _a.sent();
                    if (!robot) {
                        console.warn("!robot");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Room.addUser(this.app, room, robot, true)];
                case 4:
                    room = _a.sent();
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
remote.leave = function (roomId, uid, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var room, user;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 1:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 2:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, User.leaveRoom(this.app, user, room, true)];
                case 3:
                    _a.sent();
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
remote.sendMessage = function (roomId, uid, message, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var room, user, player;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    message = common.validMessage(message);
                    return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 1:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 2:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb();
                        return [2 /*return*/];
                    }
                    player = room.players.find(function (p) { return !!p && p.user._id.equals(user._id); });
                    if (!player) {
                        console.warn("!player");
                        cb();
                        return [2 /*return*/];
                    }
                    if (!room.isStart || (player && player.isSpeaking)) {
                        Room.pushRoomEvent(this.app, room, "玩家讯息", {
                            userName: User.getName(user),
                            userId: user._id,
                            playerNumber: room.players.findIndex(function (p) { return !!p && !!player && p._id.equals(player._id); }) + 1,
                            message: message,
                        });
                    }
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
remote.sendWolfMessage = function (roomId, uid, type, number, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var room, player;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 1:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb();
                        return [2 /*return*/];
                    }
                    if (!room.isStart) {
                        console.warn("!room.isStart");
                        cb();
                        return [2 /*return*/];
                    }
                    if (room.isMorning) {
                        console.warn("room.isMorning");
                        cb();
                        return [2 /*return*/];
                    }
                    player = room.players.find(function (p) { return !!p && p.user._id.toString() == uid; });
                    if (!player) {
                        console.warn("!player");
                        cb();
                        return [2 /*return*/];
                    }
                    if (player.role != "狼人") {
                        console.warn("player.role != 狼人");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Room.pushRoomEvent(this.app, room, "狼讯息", {
                            fromNumber: room.players.findIndex(function (p) { return !!p && p.user._id.toString() == uid; }) + 1,
                            number: number,
                            type: type,
                        }, function (player) { return player.role == "狼人"; })];
                case 2:
                    _a.sent();
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
remote.sendBullet = function (roomId, uid, message, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var room;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    message = common.validMessage(message);
                    return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 1:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb();
                        return [2 /*return*/];
                    }
                    Room.pushRoomEvent(this.app, room, "弹幕", {
                        message: message,
                    });
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
remote.stopSpeak = function (roomId, uid, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var room, user, player;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 1:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 2:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb();
                        return [2 /*return*/];
                    }
                    player = room.players.find(function (p) { return !!p && p.user._id.equals(user._id); });
                    if (!player) {
                        console.warn("!player");
                        cb();
                        return [2 /*return*/];
                    }
                    if (!room.isMorning || !player.isSpeaking) {
                        console.warn("!room.isMorning || !player.isSpeaking");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Room.cancelWait(this.app, room)];
                case 3:
                    room = _a.sent();
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
/**
 * @see  放弃上警/ 退水
 */
remote.withdrawn = function (roomId, uid, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var room, user, player;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 1:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb();
                        return [2 /*return*/];
                    }
                    if (!room.enableWithdrawn) {
                        console.warn("!room.enableWithdrawn");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 2:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb();
                        return [2 /*return*/];
                    }
                    player = room.players.find(function (p) { return !!p && p.user._id.equals(user._id); });
                    if (!player) {
                        console.warn("!player");
                        cb();
                        return [2 /*return*/];
                    }
                    if (player.leaderState != 1) {
                        console.warn("player.leaderState != 1");
                        cb();
                        return [2 /*return*/];
                    }
                    player.leaderState = 2;
                    return [4 /*yield*/, Room.sync(this.app, room)];
                case 3:
                    room = _a.sent();
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
/**
 * @see  猎人死亡 触发技能 111111
 */
remote.hunterGun = function (roomId, uid, isGun, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var room, user, player;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 1:
                    room = _a.sent();
                    //不存在room对象退出
                    if (!room) {
                        console.warn("!room");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 2:
                    user = _a.sent();
                    //如果用户不存在  那么退出
                    if (!user) {
                        console.warn("!user");
                        cb();
                        return [2 /*return*/];
                    }
                    player = room.players.find(function (p) { return !!p && p.user._id.equals(user._id); });
                    if (!player) {
                        console.warn("!player");
                        cb();
                        return [2 /*return*/];
                    }
                    if (player.role != "猎人") {
                        console.warn("player.role!=猎人");
                        cb();
                        return [2 /*return*/];
                    }
                    //如果用户点击了发动技能   传进来是true 那么发动猎人行动  流程
                    //标准模式   最后一个狼  杀了最后一个猎人 猎人不能发动技能------>影响 成功判断
                    if (room.mode == 2 && room.players.find(function (p) { return !!p && p.deadInfo.state > 0 && (p.role == "女巫" || p.role == "预言家" || p.role == "白痴"); })) {
                        isGun = false;
                    }
                    if (!isGun)
                        return [3 /*break*/, 5];
                    return [4 /*yield*/, Room.cancelWait(this.app, room, false, false)];
                case 3:
                    /**
                     * 停止旧的定时器
                     * @see  ：  停止原有的流程  直接调到猎人行到
                     *
                     * 没有等待时间
                     */
                    room = _a.sent();
                    return [4 /*yield*/, Room.nextRound(this.app, room, "猎人行动")];
                case 4:
                    _a.sent();
                    _a.label = 5;
                case 5:
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
remote.kickPlayer = function (roomId, uid, kickPid, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var room, kickPlayer;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 1:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb();
                        return [2 /*return*/];
                    }
                    if (room.isStart) {
                        console.warn("room.isStart");
                        cb();
                        return [2 /*return*/];
                    }
                    if (!Room.isOwnerEquals(room, uid)) {
                        console.warn("(!Room.isOwnerEquals(room, player.user._id)");
                        cb();
                        return [2 /*return*/];
                    }
                    kickPlayer = room.players.find(function (p) { return !!p && p._id.equals(kickPid); });
                    if (!kickPlayer) {
                        console.warn("!kickPlayer");
                        cb();
                        return [2 /*return*/];
                    }
                    if (kickPlayer.user._id.equals(uid)) {
                        console.warn("kickPlayer.user._id.equals(uid)");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Room.kickPlayer(this.app, room, kickPid)];
                case 2:
                    room = _a.sent();
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
remote.inviteUsers = function (sender, roomId, userIds, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var room, msg, friendIds, i, userId, friend, allUserIds, statusService;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!userIds || userIds.length == 0) {
                        console.warn("!userIds || userIds.length == 0");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 1:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb();
                        return [2 /*return*/];
                    }
                    if (room.isStart) {
                        console.warn("room.isStart");
                        cb();
                        return [2 /*return*/];
                    }
                    msg = {
                        sender: sender,
                        sendAt: new Date().valueOf(),
                        number: room.number,
                        playerCount: room.players.length,
                    };
                    friendIds = [];
                    i = 0;
                    _a.label = 2;
                case 2:
                    if (!(i < userIds.length))
                        return [3 /*break*/, 6];
                    userId = userIds[i];
                    return [4 /*yield*/, Friend.find(new mongodb.ObjectID(sender), new mongodb.ObjectID(userId))];
                case 3:
                    friend = _a.sent();
                    if (friend) {
                        friend.roomInvites.push(msg);
                        friendIds.push(friend._id.toString());
                    }
                    return [4 /*yield*/, friend.save()];
                case 4:
                    friend = _a.sent();
                    _a.label = 5;
                case 5:
                    i++;
                    return [3 /*break*/, 2];
                case 6:
                    allUserIds = userIds;
                    allUserIds.push(sender);
                    statusService = this.app.get('statusService');
                    statusService.pushByUids(allUserIds, "onSendRoomInvite", {
                        friendIds: friendIds,
                        // sender: sender,
                        // recipients: userIds,
                        message: msg,
                    }, function (err, fails) {
                        cb();
                    });
                    return [2 /*return*/];
            }
        });
    });
};
/**
 * 跳过当前回合
 */
remote.stopWait = function (roomId, uid, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var room;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 1:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Room.cancelWait(this.app, room)];
                case 2:
                    // let user = await User.Model.findById(uid).exec();
                    // if (!user) { console.warn("!user"); cb(); return; }
                    // if (!user.isTester) { console.warn("!user.isTester"); cb(); return; }
                    room = _a.sent();
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
remote.bindMemberId = function (roomId, uid, memberId, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var room, player;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!memberId) {
                        console.warn("!memberId");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 1:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb();
                        return [2 /*return*/];
                    }
                    player = room.players.find(function (p) { return !!p && p.user._id.toString() == uid; });
                    if (!player) {
                        console.warn("!player");
                        cb();
                        return [2 /*return*/];
                    }
                    player.memberId = memberId;
                    return [4 /*yield*/, Room.sync(this.app, room)];
                case 2:
                    room = _a.sent();
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
remote.giveItem = function (roomId, userIdFrom, playerIdTo, itemId, isBuy, isCombo, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var room, playerTo, userFrom, userTo, game, itemData, item, giftRecord;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 1:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb();
                        return [2 /*return*/];
                    }
                    playerTo = room.players.find(function (p) { return !!p && p._id.toString().trim() == playerIdTo.toString().trim(); });
                    return [4 /*yield*/, User.Model.findById(userIdFrom).exec()];
                case 2:
                    userFrom = _a.sent();
                    if (!userFrom) {
                        console.warn("!userFrom");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, User.Model.findById(playerTo.user._id).exec()];
                case 3:
                    userTo = _a.sent();
                    if (!userTo) {
                        console.warn("!userTo");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Game.Model.findOne({})];
                case 4:
                    game = _a.sent();
                    itemData = game.items.find(function (i) { return i.id == itemId; });
                    if (!itemData) {
                        console.warn("!itemData");
                        cb();
                        return [2 /*return*/];
                    }
                    if (!isBuy) {
                        item = userFrom.inventory.find(function (i) { return i.id == itemId; });
                        if (!item) {
                            console.warn("!item");
                            cb();
                            return [2 /*return*/];
                        }
                        if (item.amount < 1) {
                            console.warn("item.amount < 1");
                            cb();
                            return [2 /*return*/];
                        }
                        userFrom = User.removeItem(userFrom, itemId, 1);
                    }
                    else {
                        if (itemData.price <= 0) {
                            console.warn("itemData.price <= 0");
                            cb();
                            return [2 /*return*/];
                        }
                        if (userFrom.currencys.gold < itemData.price) {
                            console.warn("userFrom.currencys.gold < itemData.price");
                            cb();
                            return [2 /*return*/];
                        }
                        userFrom.currencys.gold -= itemData.price;
                    }
                    if (!(isCombo && userFrom.lastGiftRecord))
                        return [3 /*break*/, 10];
                    return [4 /*yield*/, GiftRecord.Model.findById(userFrom.lastGiftRecord)];
                case 5:
                    giftRecord = _a.sent();
                    if (!(giftRecord.item.id == itemId && giftRecord.userTo.equals(userTo._id)))
                        return [3 /*break*/, 7];
                    giftRecord.item.amount++;
                    giftRecord.endAt = Date.now();
                    return [4 /*yield*/, giftRecord.save()];
                case 6:
                    giftRecord = _a.sent();
                    return [3 /*break*/, 9];
                case 7: return [4 /*yield*/, GiftRecord.create(userFrom, userTo._id, itemId)];
                case 8:
                    giftRecord = _a.sent();
                    userFrom.lastGiftRecord = giftRecord._id;
                    _a.label = 9;
                case 9: return [3 /*break*/, 12];
                case 10: return [4 /*yield*/, GiftRecord.create(userFrom, userTo._id, itemId)];
                case 11:
                    giftRecord = _a.sent();
                    userFrom.lastGiftRecord = giftRecord._id;
                    _a.label = 12;
                case 12:
                    userTo = User.addGift(userTo, itemId);
                    userTo.popularity += itemData.popularity;
                    userFrom.givenPopularity += itemData.popularity;
                    return [4 /*yield*/, User.sync(this.app, userTo)];
                case 13:
                    userTo = _a.sent();
                    return [4 /*yield*/, User.sync(this.app, userFrom)];
                case 14:
                    userFrom = _a.sent();
                    return [4 /*yield*/, Room.pushRoomEvent(this.app, room, "赠送物品", {
                            _id: userFrom.lastGiftRecord,
                            userFrom: {
                                _id: userFrom._id,
                                name: User.getName(userFrom),
                                iconPath: User.getIconPath(userFrom),
                            },
                            userIdTo: userTo._id,
                            playerIdTo: playerIdTo,
                            itemId: giftRecord.item.id,
                            iconPath: itemData.iconPath,
                            itemName: itemData.name,
                            combo: giftRecord.item.amount,
                        })];
                case 15:
                    _a.sent();
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
/**
 * @see   插入用户的送礼和收礼的信息   送礼也就是购买过程
 */
remote.giveRealItem = function (roomId, userIdFrom, playerIdTo, itemId, isBuy, isCombo, isRealGoods, 
    // addressInfo: string,
    cb) {
    return __awaiter(this, void 0, void 0, function () {
        var room, playerTo, userFrom, userTo, game, itemData, item, giftRecord, userFromName, receiveName, userFromId, userToId, goodId, goodName, goodNumber, costType, goodOneCost, goodAllCost, addressInfo;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 1:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb();
                        return [2 /*return*/];
                    }
                    playerTo = room.players.find(function (p) { return !!p && p._id.toString() == playerIdTo; });
                    if (!playerTo) {
                        console.warn("!playerTo");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, User.Model.findById(userIdFrom).exec()];
                case 2:
                    userFrom = _a.sent();
                    if (!userFrom) {
                        console.warn("!userFrom");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, User.Model.findById(playerTo.user._id).exec()];
                case 3:
                    userTo = _a.sent();
                    if (!userTo) {
                        console.warn("!userTo");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Game.Model.findOne({})];
                case 4:
                    game = _a.sent();
                    if (!game) {
                        console.warn("!game");
                        cb();
                        return [2 /*return*/];
                    }
                    // if (addressInfo == "" || addressInfo == undefined || addressInfo == null) {
                    // 	console.warn("!addressInfo");
                    // 	cb();
                    // 	return;
                    // }
                    console.warn("=============itemIditemIditemIditemId=============" + itemId);
                    console.warn("=============itemIditemIditemIditemId=============" + itemId);
                    console.warn("=============itemIditemIditemIditemId=============" + itemId);
                    console.warn("=============itemIditemIditemIditemId=============" + itemId);
                    console.warn("=============itemIditemIditemIditemId=============" + itemId);
                    itemData = game.realItems.find(function (i) { return i.id == itemId; });
                    if (!itemData) {
                        console.warn("!itemData");
                        cb();
                        return [2 /*return*/];
                    }
                    if (!isBuy) {
                        item = userFrom.inventory.find(function (i) { return i.id == itemId; });
                        if (!item) {
                            console.warn("!item");
                            cb();
                            return [2 /*return*/];
                        }
                        if (item.amount < 1) {
                            console.warn("item.amount < 1");
                            cb();
                            return [2 /*return*/];
                        }
                        userFrom = User.removeItem(userFrom, itemId, 1);
                    }
                    else {
                        if (itemData.price <= 0) {
                            console.warn("itemData.price <= 0");
                            cb();
                            return [2 /*return*/];
                        }
                        if (userFrom.currencys.gold < itemData.price) {
                            console.warn("userFrom.currencys.gold < itemData.price");
                            cb();
                            return [2 /*return*/];
                        }
                        userFrom.currencys.gold -= itemData.price;
                    }
                    if (!(isCombo && userFrom.lastGiftRecord))
                        return [3 /*break*/, 10];
                    return [4 /*yield*/, GiftRecord.Model.findById(userFrom.lastGiftRecord)];
                case 5:
                    giftRecord = _a.sent();
                    if (!(giftRecord.item.id == itemId && giftRecord.userTo.equals(userTo._id)))
                        return [3 /*break*/, 7];
                    giftRecord.item.amount++;
                    giftRecord.endAt = Date.now();
                    return [4 /*yield*/, giftRecord.save()];
                case 6:
                    giftRecord = _a.sent();
                    return [3 /*break*/, 9];
                case 7: return [4 /*yield*/, GiftRecord.create(userFrom, userTo._id, itemId)];
                case 8:
                    giftRecord = _a.sent();
                    userFrom.lastGiftRecord = giftRecord._id;
                    _a.label = 9;
                case 9: return [3 /*break*/, 12];
                case 10: return [4 /*yield*/, GiftRecord.create(userFrom, userTo._id, itemId)];
                case 11:
                    giftRecord = _a.sent();
                    userFrom.lastGiftRecord = giftRecord._id;
                    _a.label = 12;
                case 12:
                    userTo = User.addGift(userTo, itemId);
                    userTo.popularity += itemData.popularity;
                    userFrom.givenPopularity += itemData.popularity;
                    userFromName = User.getName(userFrom);
                    receiveName = User.getName(userTo);
                    userFromId = userFrom._id;
                    userToId = playerTo.user._id;
                    goodId = itemId;
                    goodName = itemData.name;
                    goodNumber = 1;
                    costType = "gold";
                    goodOneCost = itemData.price;
                    goodAllCost = goodNumber * goodOneCost;
                    addressInfo = userFrom.addressInfo.address;
                    return [4 /*yield*/, RealGitRecordInfo.insertItem(addressInfo, userFromId, userFromName, userToId, receiveName, goodId, goodName, costType, goodNumber, goodOneCost, goodAllCost)];
                case 13:
                    _a.sent();
                    return [4 /*yield*/, User.sync(this.app, userTo)];
                case 14:
                    userTo = _a.sent();
                    return [4 /*yield*/, User.sync(this.app, userFrom)];
                case 15:
                    userFrom = _a.sent();
                    return [4 /*yield*/, Room.pushRoomEvent(this.app, room, "赠送物品", {
                            _id: userFrom.lastGiftRecord,
                            userFrom: {
                                _id: userFrom._id,
                                name: User.getName(userFrom),
                                iconPath: User.getIconPath(userFrom),
                            },
                            userIdTo: userTo._id,
                            playerIdTo: playerIdTo,
                            itemId: giftRecord.item.id,
                            itemName: itemData.name,
                            iconPath: itemData.iconPath,
                            combo: giftRecord.item.amount,
                        })];
                case 16:
                    _a.sent();
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
remote.doViewer = function (roomId, uid, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var room, playerIndex, player, viewerIndex;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 1:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb();
                        return [2 /*return*/];
                    }
                    playerIndex = room.players.findIndex(function (p) { return !!p && p.user._id.toString() == uid; });
                    if (playerIndex == -1) {
                        console.warn("playerIndex == -1");
                        cb();
                        return [2 /*return*/];
                    }
                    player = room.players[playerIndex];
                    if (!player) {
                        console.warn("!player");
                        cb();
                        return [2 /*return*/];
                    }
                    viewerIndex = room.viewers.findIndex(function (v) { return v.toString() == uid; });
                    if (viewerIndex >= 0) {
                        console.warn("viewerIndex >= 0");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Room.removePlayer(room, playerIndex)];
                case 2:
                    room = _a.sent();
                    room = Room.addViewer(room, new mongodb.ObjectID(uid));
                    return [4 /*yield*/, Room.sync(this.app, room)];
                case 3:
                    room = _a.sent();
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
remote.doPlayer = function (roomId, uid, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var room, user, playerIndex, viewerIndex, newPlayerIndex;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 1:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb();
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 2:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb();
                        return [2 /*return*/];
                    }
                    playerIndex = room.players.findIndex(function (p) { return !!p && p.user._id.toString() == uid; });
                    if (playerIndex >= 0) {
                        console.warn("playerIndex >= 0");
                        cb();
                        return [2 /*return*/];
                    }
                    viewerIndex = room.viewers.findIndex(function (v) { return v.toString() == uid; });
                    if (viewerIndex == -1) {
                        console.warn("viewerIndex == -1");
                        cb();
                        return [2 /*return*/];
                    }
                    newPlayerIndex = room.players.findIndex(function (p) { return !p; });
                    if (newPlayerIndex == -1) {
                        console.warn("newPlayerIndex == -1");
                        cb();
                        return [2 /*return*/];
                    }
                    room.players[newPlayerIndex] = Player.create(user, false);
                    room.viewers.splice(viewerIndex, 1);
                    return [4 /*yield*/, Room.sync(this.app, room)];
                case 3:
                    room = _a.sent();
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
remote.close = function (roomId, uid, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var room;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 1:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb();
                        return [2 /*return*/];
                    }
                    if (!Room.isOwnerEquals(room, uid)) {
                        console.warn("!Room.isOwnerEquals(room, uid)");
                        cb();
                        return [2 /*return*/];
                    }
                    room.dayRounds = [];
                    return [4 /*yield*/, Room.pushRoomEvent(this.app, room, "主播离开")];
                case 2:
                    _a.sent();
                    return [4 /*yield*/, Room.pushEvent(this.app, room, "onSyncRoom", {})];
                case 3:
                    _a.sent();
                    return [4 /*yield*/, Room.initLiveRoom(room)];
                case 4:
                    room = _a.sent();
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
/**
 * 获取主播房间数据
 */
remote.getAnchorRoomInfos = function (uid, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var user, rooms, infos, _loop_2, i;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 1:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb([]);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, Room.Model.find({
                            isLive: true,
                            isOpen: true,
                        })];
                case 2:
                    rooms = _a.sent();
                    infos = [];
                    _loop_2 = function (i) {
                        var room, info, anchor_1, anchorPlayer, followersCount;
                        return __generator(this, function (_a) {
                            switch (_a.label) {
                                case 0:
                                    room = rooms[i];
                                    info = {
                                        isFollow: false,
                                        room: {
                                            number: room.number,
                                            mode: room.index,
                                            isStart: room.isStart,
                                            playersCount: room.players.length,
                                            viewersCount: room.viewers.length,
                                            title: room.title,
                                            coverUrl: room.coverUrl,
                                        },
                                        anchor: {
                                            _id: "",
                                            name: "",
                                            isMale: true,
                                            iconPath: "",
                                            coverUrl: "",
                                            followersCount: 0,
                                            isOnline: false,
                                        }
                                    };
                                    if (!!!room.owner)
                                        return [3 /*break*/, 3];
                                    return [4 /*yield*/, User.Model.findById(room.owner)];
                                case 1:
                                    anchor_1 = _a.sent();
                                    anchorPlayer = room.players.find(function (p) { return !!p && p.user._id.equals(anchor_1._id); });
                                    return [4 /*yield*/, User.Model.count({
                                            following: { $in: [anchor_1._id] },
                                        })];
                                case 2:
                                    followersCount = _a.sent();
                                    info.isFollow = user.following.findIndex(function (f) { return f.equals(anchor_1._id); }) >= 0;
                                    info.anchor = {
                                        _id: anchor_1._id.toString(),
                                        name: User.getName(anchor_1),
                                        isMale: User.getIsMale(anchor_1),
                                        iconPath: User.getIconPath(anchor_1),
                                        coverUrl: anchor_1.coverUrl,
                                        followersCount: followersCount,
                                        isOnline: !!anchorPlayer ? anchorPlayer.isOnline : false,
                                    };
                                    _a.label = 3;
                                case 3:
                                    infos.push(info);
                                    return [2 /*return*/];
                            }
                        });
                    };
                    i = 0;
                    _a.label = 3;
                case 3:
                    if (!(i < rooms.length))
                        return [3 /*break*/, 6];
                    return [5 /*yield**/, _loop_2(i)];
                case 4:
                    _a.sent();
                    _a.label = 5;
                case 5:
                    i++;
                    return [3 /*break*/, 3];
                case 6:
                    cb(infos);
                    return [2 /*return*/];
            }
        });
    });
};
remote.buySeat = function (roomId, uid, price, index, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var room, user, player, viewerIndex, oldPlayer;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 1:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb(-1);
                        return [2 /*return*/];
                    }
                    if (!room.isLive) {
                        console.warn("!room.isLive");
                        cb(-1);
                        return [2 /*return*/];
                    }
                    if (room.seatPrices[index] < 0) {
                        console.warn("room.seatPrices[index] < 0");
                        cb(-1);
                        return [2 /*return*/];
                    }
                    if (room.seatPrices[index] != price) {
                        console.warn("room.seatPirces[index] != price");
                        cb(-1);
                        return [2 /*return*/];
                    }
                    return [4 /*yield*/, User.Model.findById(uid).exec()];
                case 2:
                    user = _a.sent();
                    if (!user) {
                        console.warn("!user");
                        cb(0);
                        return [2 /*return*/];
                    }
                    player = room.players.find(function (p) { return !!p && p.user._id.equals(user._id); });
                    if (!!player) {
                        console.warn("!!player");
                        cb(-1);
                        return [2 /*return*/];
                    }
                    viewerIndex = room.viewers.findIndex(function (v) { return v.toString() == uid; });
                    if (viewerIndex == -1) {
                        console.warn("viewerIndex == -1");
                        cb(-1);
                        return [2 /*return*/];
                    }
                    oldPlayer = room.players[index];
                    return [4 /*yield*/, Room.pushRoomEvent(this.app, room, "位置被抢", {
                            oldUserId: !!oldPlayer ? oldPlayer.user._id.toString() : "",
                            newUserName: User.getName(user),
                            price: price,
                            number: index + 1,
                        })];
                case 3:
                    _a.sent();
                    if (!!!oldPlayer)
                        return [3 /*break*/, 5];
                    room = Room.addViewer(room, oldPlayer.user._id);
                    return [4 /*yield*/, oldPlayer.remove()];
                case 4:
                    oldPlayer = _a.sent();
                    room.players.splice(index, 0, null);
                    _a.label = 5;
                case 5:
                    user.currencys.gold -= price;
                    room.players[index] = Player.create(user, false);
                    room.seatPrices[index] *= 2;
                    room.viewers.splice(viewerIndex, 1);
                    return [4 /*yield*/, User.sync(this.app, user)];
                case 6:
                    user = _a.sent();
                    return [4 /*yield*/, Room.sync(this.app, room)];
                case 7:
                    room = _a.sent();
                    cb(1);
                    return [2 /*return*/];
            }
        });
    });
};
/**
 * 玩家点击自爆的时候  进入的方法
 *
 */
remote.exposure = function (roomId, uid, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var room, player, playerNumber;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 1:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb();
                        return [2 /*return*/];
                    }
                    if (!room.isMorning) {
                        console.warn("!room.isMorning");
                        cb();
                        return [2 /*return*/];
                    }
                    player = room.players.find(function (p) { return !!p && p.user._id.toString() == uid; });
                    if (!player) {
                        console.warn("!player");
                        cb();
                        return [2 /*return*/];
                    }
                    if (player.deadInfo.state != 0) {
                        console.warn("player.deadInfo.state != 0");
                        cb();
                        return [2 /*return*/];
                    }
                    if (!(player.role == "狼人" || player.role == "刺客")) {
                        console.warn("player.role != 狼人");
                        cb();
                        return [2 /*return*/];
                    }
                    if (player.leaderState == 3) {
                        player.leaderState = 0;
                    }
                    playerNumber = room.players.indexOf(player) + 1;
                    /**
                     * @pushRoomEvent : 当玩家死亡  后端发给前端的数据
                     */
                    //  Room 
                    // let alivePlayers: Player.Document[] = room.players.filter(p => !!p && p.deadInfo.state == 0) as Player.Document[];
                    // let deadPlayers: Player.Document[] = alivePlayers.filter(p => p.deadInfo.state > 0);
                    // await Room.pushRoomEvent(this.app, room, "多个玩家死亡", { 'numbers': deadPlayers.map(p => room.players.indexOf(p) + 1) });
                    return [4 /*yield*/, Room.pushRoomEvent(this.app, room, "狼人自曝", { number: playerNumber })];
                case 2:
                    /**
                     * @pushRoomEvent : 当玩家死亡  后端发给前端的数据
                     */
                    //  Room 
                    // let alivePlayers: Player.Document[] = room.players.filter(p => !!p && p.deadInfo.state == 0) as Player.Document[];
                    // let deadPlayers: Player.Document[] = alivePlayers.filter(p => p.deadInfo.state > 0);
                    // await Room.pushRoomEvent(this.app, room, "多个玩家死亡", { 'numbers': deadPlayers.map(p => room.players.indexOf(p) + 1) });
                    _a.sent();
                    return [4 /*yield*/, Room.killPlayer(this.app, room, player._id, 6)];
                case 3:
                    room = _a.sent();
                    return [4 /*yield*/, Room.cancelWait(this.app, room, false, false)];
                case 4:
                    room = _a.sent();
                    if (!Room.getWinner(room))
                        return [3 /*break*/, 6];
                    /**
                     * @nextRound :  进入下一个 流程
                     */
                    return [4 /*yield*/, Room.nextRound(this.app, room, "游戏结束")];
                case 5:
                    /**
                     * @nextRound :  进入下一个 流程
                     */
                    _a.sent();
                    return [3 /*break*/, 8];
                case 6: return [4 /*yield*/, Room.nextRound(this.app, room, "玩家死亡")];
                case 7:
                    _a.sent();
                    _a.label = 8;
                case 8:
                    // else if (room.dayRounds.indexOf("玩家死亡") == -1) {
                    // 	await Room.nextRound(this.app, room, "玩家死亡");
                    // }
                    // else {
                    // 	await Room.nextRound(this.app, room, "天黑");
                    // }
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
// remote.changeSeat = async function(roomId, uid, seatIndex, cb) {
// 	let room = await Room.Model.findById(roomId).exec();
// 	if (!room) { console.warn("!room"); cb(); return; }
// 	if (!!room.players[seatIndex]) { console.warn("!!room.players[seatIndex]"); cb(); return; }
// 	let playerIndex = room.players.findIndex(p => !!p && p.user._id.toString() == uid);
// 	let player = room.players.find(p => !!p && p.user._id.toString() == uid);
// 	if (!player) { console.warn("!player"); cb(); return; }
// 	room.players[seatIndex] = player;
// 	room.players[playerIndex] = null;
// 	room = await Room.sync(this.app, room);
// 	cb();
// };
remote.changeSeat = function (playerId, roomId, uid, seatIndex, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var room, playerIndex, player;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 1:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb();
                        return [2 /*return*/];
                    }
                    if (!!room.players[seatIndex]) {
                        console.warn("!!room.players[seatIndex]");
                        cb();
                        return [2 /*return*/];
                    }
                    playerIndex = room.players.findIndex(function (p) { return !!p && p.user._id.toString() == uid; });
                    player = room.players.find(function (p) { return !!p && p.user._id.toString() == uid; });
                    if (!player) {
                        console.warn("!player");
                        cb();
                        return [2 /*return*/];
                    }
                    room.players[seatIndex] = player;
                    room.players[playerIndex] = null;
                    return [4 /*yield*/, Room.sync(this.app, room)];
                case 2:
                    room = _a.sent();
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
/**
 * @see 玩家点击跳过当前步骤
 */
remote.skipCurrentStep2 = function (roomId, uid, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var room, player, isAllConfirm;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Room.Model.findById(roomId).exec()];
                case 1:
                    room = _a.sent();
                    if (!room) {
                        console.warn("!room");
                        cb();
                        return [2 /*return*/];
                    }
                    player = room.players.find(function (p) { return !!p && p.user._id.equals(uid); });
                    if (!player) {
                        console.warn("!player");
                        cb(0);
                        return [2 /*return*/];
                    }
                    player.isConfirmSkip = true;
                    return [4 /*yield*/, room.save()];
                case 2:
                    _a.sent();
                    isAllConfirm = !room.players.find(function (p) { return !!p && !p.isRobot && p.selectedPlayers.length > 0 && !p.isConfirmSkip; });
                    if (!isAllConfirm)
                        return [3 /*break*/, 4];
                    return [4 /*yield*/, Room.cancelWait(this.app, room)];
                case 3:
                    _a.sent();
                    _a.label = 4;
                case 4:
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
/**
 * @see   白痴插话功能
 */
remote.skipFoolSpeaking = function (msg, cb) {
    return __awaiter(this, void 0, void 0, function () {
        var room;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0: return [4 /*yield*/, Room.Model.findById(msg.roomId).exec()];
                case 1:
                    room = _a.sent();
                    if (!room) {
                        console.warn("skipFoolSpeaking  do not  exist room data!");
                        cb();
                        return [2 /*return*/];
                    }
                    //判断是否存在 白痴  并且  白痴被放逐
                    room.isFoolSpeaking = true;
                    return [4 /*yield*/, Room.sync(this.app, room)];
                case 2:
                    //将数据 推送给 后端
                    // await room.save();
                    //  将数据推送给 前端
                    room = _a.sent();
                    // this.app.set("isFoolSpeaking",true);
                    cb();
                    return [2 /*return*/];
            }
        });
    });
};
